package net.dgg.robot.task.quartz;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 网络请求、接口封装
 *
 * @author tanghom
 */
public class HttpUtil {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * timeout in millis
     */
    private static  int CONNECTION_TIMEOUT = 20 * 1000;

    public static String postJson(String url,String json) throws  IOException {
        String resultStr = "";
        // 创建一个http客户端
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个PUT请求ENCRYPT_KEY
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(CONNECTION_TIMEOUT)
                .build();
        httpPost.setConfig(requestConfig);
        // 组装数据放到HttpEntity中发送到服务器
        StringEntity entity = new StringEntity(json, "UTF-8");
        Header header = new BasicHeader("Content-Type", "application/json;charset=UTF-8");
        entity.setContentType(header);
        httpPost.setEntity(entity);
        // 向服务器发送PUT请求并获取服务器返回的结果
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回的结果可能放到InputStream中。
            InputStream inputStream = response.getEntity().getContent();
            String line = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }
        } else {
            System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
        }
        return resultStr;
    }

    public static String post(String url,Map params) throws  IOException {
        String resultStr = "";
        // 创建一个http客户端
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个PUT请求ENCRYPT_KEY
        HttpPost httpPost = new HttpPost(url);

        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(CONNECTION_TIMEOUT)
                .build();
        httpPost.setConfig(requestConfig);
        // 向HttpPost中加入参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        if (null != params) {
            Iterator iter = params.entrySet().iterator();
            while (iter.hasNext()) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                Object value = entry.getValue();
                value = null == value ? "" : value;
                nvps.add(new BasicNameValuePair(key, value == null ? "" : value.toString()));
            }
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        // 向服务器发送PUT请求并获取服务器返回的结果
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回的结果可能放到InputStream中。
            InputStream inputStream = response.getEntity().getContent();
            String line = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }
        } else {
            System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode());
        }
        return resultStr;
    }


    public static String get(String url) throws  IOException {
        String resultStr = "";
        // 创建一个http客户端
        CloseableHttpClient client = HttpClients.createDefault();
        // 创建一个get请求ENCRYPT_KEY
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECTION_TIMEOUT)
                .setConnectTimeout(CONNECTION_TIMEOUT)
                .setSocketTimeout(CONNECTION_TIMEOUT)
                .build();
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
        httpGet.setConfig(requestConfig);
        // 向服务器发送PUT请求并获取服务器返回的结果
        HttpResponse response = client.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 200) {
            // 返回的结果可能放到InputStream中。
            InputStream inputStream = response.getEntity().getContent();
            String line = "";
            StringBuffer buffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            resultStr = buffer.toString();
            if (reader != null) {
                reader.close();
            }
        } else {
            System.out.println("请求服务器返回码：" + response.getStatusLine().getStatusCode()+"，"+url);
        }
        return resultStr;
    }


    /**
     * 获取企业微信token
     * @return
     */
    private String getToken(){
        String token=null;
        try {
            String getTokenUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww67d8d6130d58984a&corpsecret=Su02AwoibcKyKqHjB_fxt6L8fN1q7gE750iGby4Fdoo";
            String result = HttpUtil.get(getTokenUrl);
            Map map = JsonUtil.json2Obj(result,Map.class);
            token = (String)map.get("access_token");
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 考勤记录查询
     * @param userList 用户集合
     * @param startTime 开始时间戳
     * @param endTime 结束时间戳
     * @return
     */
    private List<Map> getCheckList( List<String> userList,Long startTime,Long endTime){
        List<Map> returnList = new ArrayList();
        try {
            String checkIndataUrl = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token="+this.getToken();
            Map<String,Object> params = new HashMap<>();
            params.put("opencheckindatatype",1);
            params.put("starttime",startTime);
            params.put("endtime",endTime);
            params.put("useridlist",userList);
            String paramJson = JsonUtil.obj2Json(params);
            logger.info(paramJson);
            String resultStr = HttpUtil.postJson(checkIndataUrl,paramJson);
            logger.info(resultStr);
            Map resultMap = JsonUtil.json2Obj(resultStr,Map.class);
            returnList = JsonUtil.json2Obj(resultMap.get("checkindata").toString(),List.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnList;
    }

    /**
     * 根据当前时间查询用户是否有打卡，上班和下班
     * @param userList
     * @return
     */
    private Map queryNowDayCheckUserList(List userList){
        Map returnMap = new HashMap();
        returnMap.put("code","0");
        returnMap.put("list",null);
        try {
            SimpleDateFormat daySdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat timeSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //当前时间
            Date now =new Date();
            String nowDayStr = daySdf.format(now);
            //上班时间
            String startWorkTimeStr = nowDayStr+" 08:30:00";
            Date startWorkTime = timeSdf.parse(startWorkTimeStr);
            //下班时间
            String endWorkTimeStr = nowDayStr+" 17:30:00";
            Date endWorkTime = timeSdf.parse(endWorkTimeStr);

            if(now.before(startWorkTime)||now.after(endWorkTime)){
                Long startTime = null;
                Long endTime = null;
                //当前时间在上班之前
                if(now.before(startWorkTime)){
                    String firstTimeStr = nowDayStr+"  00:00:00";
                    Date firstDate = timeSdf.parse(firstTimeStr);
                    startTime=getSecondTime(firstDate);
                    endTime=getSecondTime(startWorkTime);
                }
                //当前时间在下班之后
                if(now.after(endWorkTime)){
                    String overTimeStr = nowDayStr+"  23:59:59";
                    Date overDate = timeSdf.parse(overTimeStr);
                    startTime=getSecondTime(endWorkTime);
                    endTime=getSecondTime(overDate);
                }
                logger.info("开始时间戳："+startTime+"，结束时间戳："+endTime);
                List<Map> resultList = this.getCheckList(userList,startTime,endTime);
                List completeList = new ArrayList();
                for (int i = 0; i < resultList.size(); i++) {
                    Map comMap = resultList.get(i);
                    String userid = comMap.get("userid").toString();
                    completeList.add(userid);
                }
                returnMap.put("code","1");
                returnMap.put("list",completeList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * 查询未打卡名单
     * @return
     */
    public List queryNoClockInUserList(String filePath){
        List notList = new ArrayList();
        if(!"".equals(filePath)){
            String userMapJson= new HttpUtil().getUsers(filePath);
            logger.info(userMapJson);
            Map<String,String> map = new HashMap();
            map = JsonUtil.json2Obj(userMapJson,Map.class);
            Set set =  map.keySet();
            List<String> userList = new ArrayList<>(set);
            Map completeMap = this.queryNowDayCheckUserList(userList);
            if("1".equals(completeMap.get("code"))){
                List<String> completeList = (List)completeMap.get("list");
                for (int i = 0; i < completeList.size(); i++) {
                    String userId=completeList.get(i).toString();
                    map.remove(userId);
                }
                notList=new ArrayList();
                for (String key:map.keySet() ) {
                    notList.add(key);
                }
            }
        }
        return notList;
    }

    /**
     * 获取秒时间戳
     * @param date
     * @return
     */
    private static Long getSecondTime(Date date){
        String timestamp = String.valueOf(date.getTime());
        int length = timestamp.length();
        if (length > 3) {
            return Long.valueOf(timestamp.substring(0,length-3));
        } else {
            return 0L;
        }
    }

    private String getUsers(String filePath){
        StringBuilder result = new StringBuilder();
        try{
//            String filePath = this.getClass().getClassLoader().getResource("./user.txt").getPath();
            File file = new File(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 获取随机一言
     * @return
     */
    public static String getYiyan(){
        String hitokotoUrl = "https://v1.hitokoto.cn/?encode=text";
        String btstuUrl = "http://api.btstu.cn/yan/api.php";
        String alapiUrl = "https://v1.alapi.cn/api/soul?format=text";
        String yiyan = null;
        try {
            Map map = new HashMap();
            map.put(1,hitokotoUrl);
            map.put(2,btstuUrl);
            map.put(3,alapiUrl);
            //创建一个Random类对象实例
            Random rd = new Random();
            int x = rd.nextInt(3)+1;
            String url = (String) map.get(x);
            yiyan = HttpUtil.get(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return yiyan;
    }

    /**
     * 查询当天是否工作日
     * @return
     */
    public static int isWorkDay(){
        String url="https://ibosscms.dgg188.cn/api/cms/work_day/v1/find_day_is_workday.do";
        int isWorkDay=0;
        try {
            SimpleDateFormat daySdf = new SimpleDateFormat("yyyy-MM-dd");
            //当前时间
            Date now =new Date();
            String nowDayStr = daySdf.format(now);
            Map<String,Object> params = new HashMap<>();
            params.put("day",nowDayStr);
            String resultStr = HttpUtil.post(url,params);
            Map map = JsonUtil.json2Obj(resultStr,Map.class);
            isWorkDay=null!=map.get("data")?Integer.parseInt(map.get("data").toString()):0;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isWorkDay;
    }

    /**
     * 发送企业微信消息
     * @param webhookUrl
     * @param content
     */
    public void pushWorkWx(String webhookUrl,String content){
        try {
            if (!"".equals(webhookUrl)&&1==HttpUtil.isWorkDay()) {
                String yulu=HttpUtil.getYiyan();
                String json = "{\"msgtype\":\"text\",\"text\":{\"content\":\"【"+yulu+"】\r\n"+content+"\",\"mentioned_list\":[\"@all\"]}}";
                logger.info(json);
                HttpUtil.postJson(webhookUrl, json);
            } else {
                logger.info("提醒失败，未找到配置文件数据");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
//      String yulu= HttpUtil.getYiyan();
//        System.out.println(yulu);
    }

}
